package com.da.javatest.thread.juc.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author chenlida
 * @date 2020/7/11 22:30
 * @description
 */
public class Semaphore1 {
    private static Semaphore semaphore = new Semaphore(2);

    public static class MyThread extends Thread {
        public MyThread(String name) {
            super.setName(name);
        }

        @Override
        public void run() {
            Thread thread = Thread.currentThread();
            try {
                semaphore.acquire();
                System.out.println(thread.getName() + "获得许可");
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
                System.out.println(thread.getName() + "释放许可");
            }
        }
    }

    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            new MyThread("thread-" + i).start();
        }
    }
}
